import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import store from '../store'

const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 30000
})

service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code === 20001 && res.info === '登录超时') {
      removeToken()
      location.href = '/login?storeId=' + store.state.userInfo.store_id
    }

    if (res.code === 20000 || res.code === 20001 || res.code === 20002) {
      return res
    }

    return Promise.reject(new Error(res.data.info || '请稍后再试'))
  },
  error => {
    //服务器端异常
    return Promise.reject(error)
  }
)

export default service
